//
//  Network.swift
//  swiftDemo
//
//  Created by Gerry on 2021/11/18.
//

import UIKit
import Alamofire

enum MethodType {
    case GET
    case POST
}

class Network: NSObject {
    class func request(type : MethodType, urlString : String, parameters : [String : String]? = nil, callback: @escaping (_ result : AnyObject?, _ isSuccess: Bool) -> Void) {
        
        let methodType = (type == .GET) ? HTTPMethod.get : HTTPMethod.post
        guard let url : URL = URL.init(string: urlString) else {
            return
        }
        AF.request(url, method: methodType, parameters: parameters, encoder: URLEncodedFormParameterEncoder.default).responseJSON { response in
            switch response.result {
                case .success(let bin):
                    let respDict = bin as! Dictionary<String, AnyObject>
                    let error : NSNumber = respDict["error"] as! NSNumber
                    if (error.intValue != 0) {
                        callback(nil, false)
                    }
                    guard let datas = respDict["data"] as? Array<Dictionary<String, AnyObject>> else {
                        callback(nil, false)
                        return
                    }
                    
                    callback(respDict["data"], true)
                
                case .failure(let error):
                    print(error, false)
            }
        }

        
    }
    
    class func baseRequest(type: HTTPMethod, url: String, parameters:[String : String]?, headers:HTTPHeaders?=nil,  completeHandler: @escaping (_ result : Any?,  _ isSuccess : Bool) -> Void) {
        AF.request(url, method: type, parameters: parameters, headers: headers).responseJSON { response in
            
            switch response.result {
            case .success(let res):
                guard let resDict = res as? Dictionary<String, AnyObject> else {
                    completeHandler("parse res failure", false)
                    return
                }
                guard let err = resDict["error"] as? NSNumber else {
                    completeHandler("err", false)
                    return
                }
                if (err != 0) {
                    completeHandler("err != 0", false)
                    return
                }
                guard let data = resDict["data"] as? NSArray else {
                    completeHandler("data is not NSArray", false)
                    return
                }
                completeHandler(data, true)
            case .failure(let error):
                completeHandler(error.localizedDescription, false)
            }
        
//            print("\response")
            
        }
    }
}
